package com.qk.filter;

import com.qk.common.utils.CurrentUserHoler;
import com.qk.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        String uri = request.getRequestURI();// /users (获取的就是后面这一部分 不包括前面的localhost:90....)

        //2.判断是否是登录请求
        if (uri.contains("login")){
            log.info("登录请求:{}",uri);
            filterChain.doFilter(request,response);
            return;
        }
        //3.获取请求头token,
        String jwt = request.getHeader("token");

        //4.判断是否有token,不存在响应401
        if (jwt == null || jwt.isEmpty()){
            log.info("请求头没有token");
            response.setStatus(401);
            return;
        }
        //5.解析token,判断是否合法,不合法响应401
        try {
            Claims claims = JwtUtils.parseToken(jwt);
            //获取用户id
            Integer userId = claims.get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(userId);
            log.info("当前用户ID已存入ThreadLocal:{}",userId);
            log.info("解析成功:{}",claims);
        } catch (Exception e) {
            log.info("解析token异常:{}",e.getMessage());
            response.setStatus(401);
            return;
        }
        //6.放行
        filterChain.doFilter(request,response);

        //7.清除ThreadLocal
        log.info("接下来把当前用户ID从ThreadLocal清除");
        CurrentUserHoler.removeCurrentUser();
    }
}
